package com.csw.android.androidtest.net.socket.udp;

import java.util.LinkedList;

/**
 * Udp消息对象，负责分包、组包
 */
public class UDPMessage {
    //每包数据允许的最大字节数
    public static final int packetMaxLength = 1472;

    //消息id
    private byte id;
    //每包消息的长度限制
    private final int packetLength;
    //消息包数量
    private final LinkedList<Packet> packets = new LinkedList();

    public UDPMessage(byte id) {
        this(id, packetMaxLength);
    }

    public UDPMessage(byte id, int packetLength) {
        this.id = id;
        if (packetLength <= 0) {
            packetLength = packetMaxLength;
        } else if (packetLength > packetMaxLength) {
            packetLength = packetMaxLength;
        }
        this.packetLength = packetLength;
    }

    public void setData(byte[] data) {
        packets.clear();
        int dataLength = data.length;
        int maxPacketDataLength = packetLength - Packet.headBytesLength;
        int packetCount = (dataLength + maxPacketDataLength - 1) / maxPacketDataLength;
        for (int i = 0; i < packetCount; i++) {
            int start = maxPacketDataLength * i;
            int end = Math.min(dataLength, start + maxPacketDataLength);
            byte[] packetData = new byte[end - start];
            System.arraycopy(data, start, packetData, 0, packetData.length);
            addPacket(new Packet(id, i + 1 == packetCount ? 1 : 0, dataLength, packetData));
        }
    }

    public byte[] getData() {
        if (packets.size() > 0) {
            byte[] data = new byte[packets.get(0).getMessageDataLength()];
            byte[] packetData;
            int position = 0;
            for (Packet packet : packets) {
                packetData = packet.getData();
                System.arraycopy(packetData, 0, data, position, packetData.length);
                position += packetData.length;
            }
            return data;
        }
        return null;
    }

    public void addPacket(Packet packet) {
        packets.add(packet);
    }

    public boolean checkDataEnable() {
        if (packets.size() > 0) {
            int dataLength = 0;
            int dataByteCount = 0;
            for (Packet packet : packets) {
                dataLength = packet.getMessageDataLength();
                dataByteCount += packet.getData().length;
            }
            if (dataLength == dataByteCount) {
                return true;
            }
        }
        return false;
    }

    public byte getId() {
        return id;
    }

    public LinkedList<Packet> getPackets() {
        return packets;
    }

}
